#include "qgooglemapviewer.h"
#include <qpainter.h>
#include <QImage>
#include <QUrl>
#include <iostream>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QMessageBox>

QGoogleMapViewer::QGoogleMapViewer(QWidget *parent) :
	QWidget(parent)
{
	bLButtonDown = false;
}

void QGoogleMapViewer::showEvent(QShowEvent *)
{
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 2; j++)
		{
			GoogleTile* tile = new GoogleTile(i, j, 1);
			connect(tile, &GoogleTile::finished, this, &QGoogleMapViewer::TileDownLoaded);
		}
	}
	viewPort.setZoomLevel(1);
}

void QGoogleMapViewer::paintEvent(QPaintEvent* event)
{
	if(0 < tileList.size())
	{
		QPainter painter(this);
		viewPort.setViewPortRect(rect());
		double resolution = GoogleTile::GetResolutionByLevel(viewPort.getZoomLevel());
		foreach (GoogleTile* tile, tileList) {
			if(NULL != tile->getMImage())
			{
				int offsetX = (int)((tile->getMGeoExtent().minx - viewPort.getGeoExtent().minx) / resolution + 0.1);
				int offsetY = (int)((viewPort.getGeoExtent().maxy - tile->getMGeoExtent().maxy) / resolution + 0.1);
				painter.drawImage(offsetX, offsetY, *(tile->getMImage()));
			}
		}
	}
}

void QGoogleMapViewer::mousePressEvent(QMouseEvent* event)
{
	preClickPt = event->pos();
	bLButtonDown = true;
}

void QGoogleMapViewer::mouseReleaseEvent(QMouseEvent* event)
{
	bLButtonDown = false;
}

void QGoogleMapViewer::mouseMoveEvent(QMouseEvent* event)
{
	if(bLButtonDown)
	{
		viewPort.Move(event->x() - preClickPt.x(), event->y() - preClickPt.y());
		preClickPt = event->pos();
		update();
	}
}

void QGoogleMapViewer::wheelEvent(QWheelEvent* event)
{
    QPoint angle = event->angleDelta();
    if(0 < angle.y())
    {
        //滚轮向上滚动
        viewPort.ZoomIn();
    }
    else
    {
        // 滚轮向下滚动
        viewPort.ZoomOut();
    }
    updateView();
}

void QGoogleMapViewer::updateView()
{
    //清空当前瓦片缓存
    foreach (GoogleTile* tile, tileList) {
        delete tile;
        tile = NULL;
    }
    tileList.clear();

    viewPort.setViewPortRect(rect());

    // 计算新的x,y取值范围
    QRect tileIndexRange = viewPort.getTileIndexRange();
    for(int i = tileIndexRange.left(); i < tileIndexRange.right(); i++)
    {
        for(int j = tileIndexRange.top(); j < tileIndexRange.bottom(); j++)
        {
            GoogleTile* tile = new GoogleTile(i, j, viewPort.getZoomLevel());
            connect(tile, &GoogleTile::finished, this, &QGoogleMapViewer::TileDownLoaded);
        }
    }

    //刷新视图
    update();
}

void QGoogleMapViewer::TileDownLoaded(GoogleTile* tile)
{
	tileList.push_back(tile);
	update();
}
